package com.xsh.opensltest;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.DialogFragment;

import com.xsh.opensltest.plugin.AarManifest;
import com.xsh.opensltest.plugin.UIParser;
import com.xsh.opensltest.plugin.XmlParser;

import java.io.File;
import java.lang.reflect.Constructor;

import dalvik.system.DexClassLoader;
// 将来重构到daw软件
public class PluginView extends DialogFragment
{
    private File UIFile;
    private String instrument_name;
    private String tag;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        tag = PluginView.class.getSimpleName();
        // 设置样式为全屏
        //setStyle(DialogFragment.STYLE_NORMAL, android.R.style.Theme_DeviceDefault_NoActionBar_Fullscreen);
    }
    public PluginView(String uiFile,String p_instrument_name)
    {
        UIFile = new File(uiFile);
        instrument_name = p_instrument_name;
    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        // 考虑应该怎么存储
        outState.putString("instrumentName",instrument_name);
        outState.putDouble("amp",1.0);
        outState.putInt("A",0);
        outState.putInt("D",0);
        outState.putInt("S",0);
        outState.putInt("R",0);
    }
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState)
    {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        // 加载插件 UI
        View view = null;
        try {
            //view = UIParser.parseUI(App.appContext,UIFile);

            // 2025/6/3 测试handler是否存在
            Log.d(tag,"开始创建界面和绑定事件");
            //使用外部经过d8 dx编译转换后的classes.jar
            File jarFile = new File(App.appFilesDir,instrument_name + File.separator + "java" + File.separator + "classesd8.jar");
            File manifestFile = new File(App.appFilesDir,instrument_name + File.separator + "config" + File.separator + "AndroidManifest.xml");
            AarManifest aarManifest = XmlParser.parseManifest(manifestFile);
            String handler_name = aarManifest.getHandlerName();
            Log.d(tag,handler_name);
            //反射并初始化handler时候，无法反射调用SlEngine.class 因为是不同的类加载器路径
            DexClassLoader dex = new DexClassLoader(jarFile.getAbsolutePath(),new File(App.appCacheDir.getAbsolutePath(),"dex").getAbsolutePath(),null,getActivity().getClassLoader());
            Class<?> HandlerClass = dex.loadClass(handler_name);
            Constructor<?> constructor = HandlerClass.getConstructor(Context.class);
            Object handlerInstance = constructor.newInstance(App.appContext);
            Log.d(tag,handlerInstance.toString());
            view = UIParser.parseUI(App.appContext,UIFile,handlerInstance);
           // SlEngine.loadPlugin(new File(App.appFilesDir,instrument_name + File.separator + "lib" + File.separator + "lib" + instrument_name+ ".so").getAbsolutePath());
        } catch (Exception e) {
            e.printStackTrace();
            Log.e(tag,e.getMessage());
            // 获取异常信息，包含类型和消息
            String exceptionType = e.getClass().getSimpleName();
            String message = e.getMessage();

            // 构造基础日志信息
            String logMessage = message != null ?
                    exceptionType + ": " + message :
                    exceptionType + " occurred";

            // 记录完整异常堆栈（自动处理null）
            Log.e("wrapperException", logMessage, e);

            // 追踪根本原因（递归处理可选）
            Throwable cause = e.getCause();
            int depth = 1;
            while (cause != null) {
                String causeLog = "Caused by (" + depth + "): " +
                        cause.getClass().getSimpleName() +
                        (cause.getMessage() != null ?
                                ": " + cause.getMessage() : "");
                Log.e("wrapperException", causeLog, cause);
                cause = cause.getCause();
                depth++;
            }
        }
        builder.setTitle("乐器界面");
        builder.setCancelable(false);
        builder.setPositiveButton("保存数据", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i)
            {
                //savedInstanceState.putInt("A",(ViewGroup)view);
            }
        });
        builder.setView(view);
        return builder.create();
    }
}
